package it.appcatalogobase;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.TargetApi;
import android.app.ActionBar.TabListener;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Main2Activity extends FragmentActivity implements TabListener {
	private ViewPager viewPager;
	private TabsPagerAdapter mAdapter;
	private android.app.ActionBar actionBar;
	// Tab titles
	private String[] tabs = { "HOME", "CATALOGO", "CHI SIAMO", "DOVE SIAMO" };
	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	String SENDER_ID = "384144619489";

	/**
	 * Tag used on log messages.
	 */
	static final String TAG = "GCM Demo";

	TextView mDisplay;
	GoogleCloudMessaging gcm;
	AtomicInteger msgId = new AtomicInteger();
	Context context;

	String regid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);
		DataAppPersistence appData = (DataAppPersistence) getApplication();
		// if (savedInstanceState == null) {
		// getSupportFragmentManager().beginTransaction().add(R.id.container,
		// new PlaceholderFragment()).commit();
		// }
		if (getIntent().getStringExtra("notifica")!=null) {
			String message = getIntent().getStringExtra("notifica");
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			final ScrollView s_view = new ScrollView(getApplicationContext());
			final TextView t_view = new TextView(getApplicationContext());
			t_view.setText(message);
			t_view.setTextSize(16);
			t_view.setTextColor(Color.BLACK);
			s_view.setPadding(5,5,5,5);
			s_view.addView(t_view);
			builder.setCancelable(false)
			.setView(s_view)
			.setTitle("Sacha Parfums")
			.setNeutralButton("Prosegui",
					new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.cancel(1);
		}else{
			if (!appData.isStarted()) {

				ConnectivityManager conMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
				NetworkInfo intC = conMgr.getActiveNetworkInfo();
				NetworkInfo intW = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				if (intC != null && intC.isConnected() && (get3gEnabled(this) || intW.isConnected())) {
					MyAsyncTask task = new MyAsyncTask("www.tempogara.it/arcobaleno/temp/catalogo.php?data=categorie", this);
					task.execute();
					// appData.setStarted(true);

				}

			}
		}
		// SharedPreferences prefs = getSharedPreferences("it.appcatalogobase",
		// Context.MODE_PRIVATE);

		// if(prefs.getBoolean("FirstSync", true))
		// Toast.makeText(this,
		// "E' necessario sincronizzare almeno una volta l'app. Vai nella sezione catalogo",
		// Toast.LENGTH_LONG).show();
		// if (savedInstanceState == null) {
		// getSupportFragmentManager().beginTransaction()
		// .add(R.id.container, new PlaceholderFragment()).commit();
		// }

		// Initilization
		viewPager = (ViewPager) findViewById(R.id.pager);
		actionBar = getActionBar();
		mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
		viewPager.setAdapter(mAdapter);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000FF")));
		actionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000FF")));
		// Adding Tabs
		for (String tab_name : tabs) {
			actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
		}

		/**
		 * on swiping the viewpager make respective tab selected
		 * */
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// on changing the page
				// make respected tab selected
				actionBar.setSelectedNavigationItem(position);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		Bundle extras = getIntent().getExtras();
		if (getIntent().getStringExtra("frag") != null) {
			String frag = extras.getString("frag");
			if (frag.equals("catalogo"))
				viewPager.setCurrentItem(1);

		}

		context = getApplicationContext();

		if (checkPlayServices()) {
			gcm = GoogleCloudMessaging.getInstance(this);
			regid = getRegistrationId(context);

			if (regid.isEmpty()) {
				ConnectivityManager conMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
				NetworkInfo intC = conMgr.getActiveNetworkInfo();

				if (intC != null && intC.isConnected()) {
					// registerInBackground();
					new AsyncTask<Void, Void, String>() {
						@Override
						protected String doInBackground(Void... params) {
							String msg = "";
							try {
								if (gcm == null) {
									gcm = GoogleCloudMessaging.getInstance(context);
								}
								regid = gcm.register(SENDER_ID);
								msg = "Device registered, registration ID=" + regid;
								// You should send the registration ID to your
								// server over
								// HTTP,
								// so it can use GCM/HTTP or CCS to send
								// messages to
								// your
								// app.
								// The request to your server should be
								// authenticated if
								// your app
								// is using accounts.
								sendRegistrationIdToBackend();

								// For this demo: we don't need to send it
								// because
								// the
								// device
								// will send upstream messages to a server that
								// echo
								// back
								// the
								// message using the 'from' address in the
								// message.

								// Persist the regID - no need to register
								// again.
								storeRegistrationId(context, regid);
							} catch (IOException ex) {
								msg = "Error :" + ex.getMessage();
								// If there is an error, don't just keep trying
								// to
								// register.
								// Require the user to click a button again, or
								// perform
								// exponential back-off.
							}
							Log.i(TAG, "result reg id:" + msg);
							return msg;
						}

						@Override
						protected void onPostExecute(String msg) {
							// mDisplay.append(msg + "\n");
						}

					}.execute(null, null, null);
					Log.i(TAG, "reg id:" + regid);
				}
			} else {
				// Toast.makeText(this, regid, Toast.LENGTH_LONG).show();
				Log.i(TAG, "reg id:" + regid);
			}
		} else {
			Log.i(TAG, "No valid Google Play Services APK found.");
		}
	}

	private boolean get3gEnabled(Context context) {
		TelephonyManager mTelephonyManager = (TelephonyManager)
				context.getSystemService(Context.TELEPHONY_SERVICE);
		int networkType = mTelephonyManager.getNetworkType();
		switch (networkType) {
		case TelephonyManager.NETWORK_TYPE_GPRS:
			return false;
		case TelephonyManager.NETWORK_TYPE_EDGE:
			return false;
		case TelephonyManager.NETWORK_TYPE_CDMA:
			return false;
		case TelephonyManager.NETWORK_TYPE_1xRTT:
			return false;
		case TelephonyManager.NETWORK_TYPE_IDEN:
			return false;
		case TelephonyManager.NETWORK_TYPE_UMTS:
			return false;
		case TelephonyManager.NETWORK_TYPE_EVDO_0:
			return false;
		case TelephonyManager.NETWORK_TYPE_EVDO_A:
			return false;
		case TelephonyManager.NETWORK_TYPE_HSDPA:
			return true;
		case TelephonyManager.NETWORK_TYPE_HSUPA:
			return true;
		case TelephonyManager.NETWORK_TYPE_HSPA:
			return true;
		case TelephonyManager.NETWORK_TYPE_EVDO_B:
			return true;
		case TelephonyManager.NETWORK_TYPE_EHRPD:
			return true;
		case TelephonyManager.NETWORK_TYPE_HSPAP:
			return true;
		case TelephonyManager.NETWORK_TYPE_LTE:
			return true;
		default:
			return false;
		}
	}


	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getGCMPreferences(context);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.isEmpty()) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	private SharedPreferences getGCMPreferences(Context context) {
		// This sample app persists the registration ID in shared preferences,
		// but
		// how you store the regID in your app is up to you.
		return getSharedPreferences(Main2Activity.class.getSimpleName(), Context.MODE_PRIVATE);
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main2, menu);
		return true;
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If it
	 * doesn't, display a dialog that allows users to download the APK from the
	 * Google Play Store or enable it in the device's system settings.
	 */
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Log.i(TAG, "This device is not supported.");
				finish();
			}
			return false;
		}
		return true;
	}

	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// // Handle action bar item clicks here. The action bar will
	// // automatically handle clicks on the Home/Up button, so long
	// // as you specify a parent activity in AndroidManifest.xml.
	// int id = item.getItemId();
	// if (id == R.id.action_settings) {
	// return true;
	// }
	// return super.onOptionsItemSelected(item);
	// }

	/**
	 * A placeholder fragment containing a simple view.
	 */
	// public static class PlaceholderFragment extends Fragment {
	//
	// public PlaceholderFragment() {
	// }
	//
	// @Override
	// public View onCreateView(LayoutInflater inflater, ViewGroup container,
	// Bundle savedInstanceState) {
	// View rootView = inflater.inflate(R.layout.fragment_main2,
	// container, false);
	// return rootView;
	// }
	// }

	@Override
	public void onTabReselected(android.app.ActionBar.Tab arg0, android.app.FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTabSelected(android.app.ActionBar.Tab arg0, android.app.FragmentTransaction arg1) {
		// Fragment fragment = null;
		// if(arg0.getPosition()==1)
		// fragment = new HomeFragment();
		// else if(arg0.getPosition()==2)
		// fragment = new ChiSiamoFragment();
		// else if(arg0.getPosition()==3)
		// fragment = new CatalogoFragment();
		viewPager.setCurrentItem(arg0.getPosition());

	}

	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and app versionCode in the application's
	 * shared preferences.
	 */
	private void registerInBackground() {
		new AsyncTask<Void, String, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regid = gcm.register(SENDER_ID);
					msg = "Device registered, registration ID=" + regid;

					// You should send the registration ID to your server over
					// HTTP,
					// so it can use GCM/HTTP or CCS to send messages to your
					// app.
					// The request to your server should be authenticated if
					// your app
					// is using accounts.
					sendRegistrationIdToBackend();

					// For this demo: we don't need to send it because the
					// device
					// will send upstream messages to a server that echo back
					// the
					// message using the 'from' address in the message.

					// Persist the regID - no need to register again.
					storeRegistrationId(context, regid);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					// If there is an error, don't just keep trying to register.
					// Require the user to click a button again, or perform
					// exponential back-off.
				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				// mDisplay.append(msg + "\n");
			}

		}.execute(null, null, null);
	}

	/**
	 * Sends the registration ID to your server over HTTP, so it can use
	 * GCM/HTTP or CCS to send messages to your app. Not needed for this demo
	 * since the device sends upstream messages to a server that echoes back the
	 * message using the 'from' address in the message.
	 */
	private void sendRegistrationIdToBackend() {
		// Your implementation here.
		// Toast.makeText(this, regid, Toast.LENGTH_LONG).show();
		AssetManager assetManager = getAssets();
		InputStream inputStream = null;
		Properties properties = new Properties();
		try {
			inputStream = assetManager.open("config.properties");
			properties.load(inputStream);
		} catch (IOException e5) {
			// TODO Auto-generated catch block
			e5.printStackTrace();
		}
		if (properties != null) {
			String urlRegId = properties.getProperty("indirizzoStoreRegId");
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlRegId);
			AccountManager accountManager = AccountManager.get(context); 
			Account account = getAccount(accountManager);
			String altro="";
			if (account != null) {
				altro+=account.name;
			}

			altro+= "|"+android.os.Build.BRAND;
			altro+= "|"+android.os.Build.MODEL;
			altro+= "|"+android.os.Build.DEVICE;
			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				nameValuePairs.add(new BasicNameValuePair("codice", regid));
				if(!altro.isEmpty())
					nameValuePairs.add(new BasicNameValuePair("altro", altro));
				// nameValuePairs.add(new BasicNameValuePair("stringdata",
				// "Hi"));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);
				Log.v("RES", response.toString());
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
		}

	}

	private static Account getAccount(AccountManager accountManager) {
		Account[] accounts = accountManager.getAccountsByType("com.google");
		Account account;
		if (accounts.length > 0) {
			account = accounts[0];      
		} else {
			account = null;
		}
		return account;
	}

	/**
	 * Stores the registration ID and app versionCode in the application's
	 * {@code SharedPreferences}.
	 * 
	 * @param context
	 *            application's  context.
	 * @param regId
	 *            registration ID
	 */
	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getGCMPreferences(context);
		int appVersion = getAppVersion(context);
		Log.i(TAG, "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
	}

	@Override
	public void onTabUnselected(android.app.ActionBar.Tab arg0, android.app.FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}

	public void listCategorie(View v) {
		Intent i = new Intent(Main2Activity.this, CategoryListActivity.class);
		startActivity(i);
	}

	public void sync(View v) {
		MyAsyncTask task = new MyAsyncTask("www.tempogara.it/arcobaleno/temp/catalogo.php?data=categorie", this);
		task.execute();
	}

	public void listAllProducts(View v) {
		Intent i = new Intent(Main2Activity.this, ListProductsActivity.class);
		i.putExtra("type", "all");
		startActivity(i);
	}

}
